package com.moefor.olive_branch.service;

import com.moefor.olive_branch.entity.Student;
import com.moefor.olive_branch.entity.User;
import com.moefor.olive_branch.repository.StudentRepository;
import com.moefor.olive_branch.repository.TeacherRepository;
import com.moefor.olive_branch.repository.UserRepostitory;
import com.moefor.olive_branch.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.apache.commons.lang3.StringUtils;

@Service
public class UserService {
    @Autowired
    private UserRepostitory userRepostitory;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @Transactional(readOnly = true)
    public User login(String username, String password) throws Exception{
        username = username.toLowerCase();
        User user = userRepostitory.findByUsername(username.toLowerCase());
        Assert.notNull(user,"用户名不存在");
        if(PasswordUtil.matches(password, user.getPassword())) return user;
        else throw new Exception("用户名或密码错误");
    }

    @Transactional
    public User add(String username, String password)throws Exception{
        username = username.toLowerCase();
        if(userRepostitory.existsByUsername(username)){
            throw new Exception("用户名已经存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(PasswordUtil.encode(password));
        user = userRepostitory.save(user);
        return user;
    }

    @Transactional
    public Student updToStudent(int userId, String no, String college, String professional, String clazz) throws Exception{
        User user = userRepostitory.findOne(userId);
        Assert.notNull(user, "用户不存在");
        if(null != user.getStudent()) throw new Exception("用户已经是学生");
        if(null != user.getTeacher()) throw new Exception("用户已经是老师");
        Student student = new Student();
        if(!StringUtils.isNumeric(no)) throw new Exception("学号格式错误");
        student.setNo(no);
        student.setCollege(college);
        student.setProfessional(professional);
        student.setClazz(clazz);
        student = studentRepository.save(student);
        return student;
    }
}
